import { join } from '../util/pathUtil'
import { promisify } from '../util/promiseUtil'
import TypeConvertor from '../type/TypeConvertor'

export class HttpRequest {
  constructor({ baseUrl }) {
    this.baseUrl = baseUrl
  }

  absUrl(url) {
    return join(this.baseUrl, url)
  }

  onBeforeRequest() {

  }

  onSuccess(res, requestParams, resolve, reject) {
    return res
  }

  onFail(ex) {
    throw ex
  }

  request(method, url, data, header = {}) {
    const requestParams = {
      method,
      url,
      data,
      header
    }
    this.onBeforeRequest(requestParams)
    return promisify(uni.request, {
      method,
      url: this.absUrl(url),
      data,
      success: (res, resolve, reject) => {
        try {
          resolve(this.onSuccess(res, requestParams, resolve, reject))
        } catch (ex) {
          try {
            this.onFail(ex)
          } catch (ex) {
            reject(ex)
          }
        }
      },
      header
    }).catch(this.onFail)
  }

  get(url, params) {
    return this.request('GET', url, params)
  }

  post(url, data) {
    return this.request('POST', url, data)
  }

  put(url, data) {
    return this.request('PUT', url, data)
  }

  delete(url, data) {
    return this.request('DELETE', url, data)
  }

  uploadFile(url, {
    filePath, name = 'file', formData, header = {}
  }) {
    this.onBeforeRequest({
      filePath,
      url,
      formData,
      header
    })
    return promisify(uni.uploadFile, {
      url,
      filePath,
      name,
      header,
      success(res, resolve, reject) {
        if (res.statusCode === 200) {
          const data = TypeConvertor.toJSON(res.data)
          resolve(data)
        }
      },
      formData
    }).then(this.onSuccess).catch(this.onFail)
  }
}

